﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using mesoBoard.Web.Core;
using mesoBoard.Services;
using mesoBoard.Data;

namespace mesoBoard.Web.Areas.Admin.Controllers
{
    public class ThemesController : mesoBoardAdminController
    {
        [HttpGet]
        public ActionResult Themes()
        {
            SetCrumb("Themes");

            ViewData["BreadCrumb"] = "Themes";
            return View(Repositories.Themes.GetThemes());
        }

        public ActionResult DeleteTheme(int ThemeID)
        {
            if (Repositories.Themes.GetDefaultTheme().ThemeID == ThemeID)
            {
                SetError("The default theme can't be deleted until a new default theme is selected");
            }
            else
            {
                Repositories.Themes.DeleteTheme(ThemeID);
                SetSuccess("Theme deleted");
            }
            return RedirectToAction("Themes");
        }

        public ActionResult SetThemeDefault(int ThemeID)
        {
            mbServices.Themes.ChangeDefaultTheme(ThemeID);
            SetSuccess("Theme default changed");
            return RedirectToAction("Themes");
        }

        [HttpGet]
        public ActionResult EditTheme(int ThemeID)
        {
            ViewData["DefaultThemeID"] = SiteConfig.BoardTheme.Value;
            SetCrumb("Themes");

            Theme TheTheme = Repositories.Themes.GetTheme(ThemeID);
            return View(TheTheme);
        }

        [HttpPost]
        public ActionResult EditTheme(Theme TheTheme, bool SetDefaultTheme)
        {
            SetCrumb("Themes");

            if (ModelState.IsValid)
            {
                Repositories.Themes.UpdateTheme(TheTheme);

                if (SetDefaultTheme)
                    mbServices.Themes.ChangeDefaultTheme(TheTheme.ThemeID);

                SetSuccess("Theme updated");
                return RedirectToAction("Themes");
            }
            else
            {
                ViewData["DefaultThemeID"] = SiteConfig.BoardTheme.Value;
                return View(TheTheme);
            }
        }

        [HttpGet]
        public ActionResult CreateTheme()
        {
            SetCrumb("Themes");

            return View();
        }

        [HttpPost]
        public ActionResult CreateTheme(Theme TheTheme, bool? SetDefaultTheme)
        {
            SetCrumb("Themes");

            if (ModelState.IsValid)
            {
                int NewThemeID = Repositories.Themes.CreateTheme(TheTheme);

                if (SetDefaultTheme.HasValue)
                    mbServices.Themes.ChangeDefaultTheme(NewThemeID);

                SetSuccess("Theme Created");
                return RedirectToAction("Themes");
            }
            else
            {
                return View();
            }
        }
    }
}
